package com.alan.camunda.boot.delegate;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
import org.camunda.bpm.engine.runtime.ActivityInstance;
import org.camunda.bpm.model.xml.type.ModelElementType;
import org.springframework.stereotype.Component;

/**
 * 在父作用域设置变量
 * 此类包含了识别是否在子流程中，是否在 CallActivity 中
 */
@Slf4j
@Component("setParentVariableDelegate")
public class SetParentVariableDelegate implements JavaDelegate {

    @Resource
    private RuntimeService runtimeService;


    @Override
    public void execute(DelegateExecution execution) throws Exception {
        log.info("in method SetParentVariableDelegate.execute()");

        String parentId = execution.getParentId();
        DelegateExecution superExecution = execution.getSuperExecution();



        if (StringUtils.isBlank(parentId) && superExecution == null) {
            log.info("不存在父执行域和父流程");
            return;
        }

        if (StringUtils.isNotBlank(parentId) ) {

            ActivityInstance actInst = execution.getProcessEngineServices().getRuntimeService().getActivityInstance(execution.getParentActivityInstanceId());
            log.info("父执行类型为：{}", actInst.getActivityType());

            log.info("在父级设置变量");
            runtimeService.setVariable(parentId, "toParent", "HelloParent");
        } else {
            log.info("设置父流程的变量");
            runtimeService.setVariable(superExecution.getId(), "toParent", "HelloParent");
        }
    }

    private boolean isInSubprocess(DelegateExecution execution) {
        // 从流程图的角度，此流程的上级元素是一个内嵌子流程
        ModelElementType parentEleType = execution.getBpmnModelElementInstance().getParentElement().getElementType();
        return parentEleType.getTypeName().equals("subProcess");

    }

    private boolean isInCallActivity(DelegateExecution execution) {
        return execution.getSuperExecution() != null;
    }






}
